<template>
  <el-container>
    <div style="padding: 10px;padding-bottom: 0">
      <div class="report_header" ref="headerHeight">
        <div style="display: flex;align-items: center">
          <div class="report_header_left"></div>
          <div style="width: 800px;display: flex;align-items: center;">
            <div class="report_header_date">
              <el-date-picker
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="report_header_query">
              <el-select v-model="query.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="未确认" value="0"></el-option>
                <el-option label="已确认" value="1"></el-option>
                <el-option label="已完成" value="2"></el-option>
                <el-option label="已取消" value="3"></el-option>
              </el-select>
            </div>
            <div class="report_header_query">
              <el-select v-model="supplierName"   value-key="id" placeholder="请选择供应商"  clearable filterable @change="changeSupp" :filter-method="remoteMethod" style="width: 100%">
                <el-option v-for="(item,index) in suppliers" style="width: 600px" :label="item.name" :value="item" :key="item.id">
                  <div style="display: flex">
                    <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                    <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toSearchSupplier">搜索供应商</div>
                </div>
                <div style="height: 30px"></div>
              </el-select>
            </div>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div
              style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px;justify-content: flex-end;">
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="单据编号"
                          v-model="query.sn" style="width: 100%"></el-input>
              </div>
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="订单编号"
                          v-model="query.orderSn" style="width: 100%"></el-input>
              </div>
            </div>
            <!-- <el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary" @click="queryClick">查询
            </el-button>

                        <div @click="chooseClick" style="width: 46px;height: 32px;background-color: #409EFF;margin-top: 7px;margin-left: 10px;border-radius: 4px;display: flex;justify-content: center;align-items: center;">
                          <i style="font-size: 24px;color: white;" :class="[queryType == false?'el-icon-caret-bottom':'el-icon-caret-top']"></i>
                        </div> -->
               <el-button style="margin-left: 10px;height: 32px;margin-top: 7px;border-top-left-radius: 4px !important;border-right: 1px solid rgb(102, 177, 255);
                border-bottom-left-radius: 4px !important;border-top-right-radius: 0px !important;border-bottom-right-radius: 0px !important;" size="small" type="primary"
                         @click="queryClick">查询
              </el-button>
              <div @click="chooseClick"
                   style="width: 25px;height: 32px;background-color: #1890ff;margin-top: 7px;display: flex;justify-content: center;
                   border-top-left-radius: 0px !important;
                border-bottom-left-radius: 0px !important;border-top-right-radius: 4px !important;border-bottom-right-radius: 4px !important;align-items: center;">
                <i style="font-size: 15px;color: white;"
                   :class="[queryType == false?'el-icon-arrow-down':'el-icon-arrow-up']"></i>
              </div>
            <!--<el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary" v-permission="['purchasein.add']" @click="addClick">新增-->
            <!--</el-button>-->
          </div>
        </div>
        <div style="width: 800px;display: flex;align-items: center;" v-show="queryType == true">
          <!--          这是放隐藏条件的容器-->
          <div class="report_header_date">
            <el-select v-model="productName" clearable placeholder="请选择商品"
                       filterable @focus="getProductList" value-key="id" :filter-method="queryProduct"  @change="changeProduct" style="width: 100%">
              <el-option v-for="item in productOptions" :key="item.id"  style="width:650px" :label="item.name" :value="item" >
                <div style="display: flex">
                  <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                  <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                  <div style="width: 200px;">
                    <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                  </div>
                </div>
              </el-option>
              <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                <div class="elOption" @click="toAddProduct">搜索商品</div>
              </div>
              <div style="height: 30px"></div>
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <div class="pd10">
      <div class="details_card" v-loadMore="[payLoads,'purchasein-list']" :style="{height:curHeight+'px'}">
        <warehouseList :warehouseForm="warehouseForm" @detailsClick="detailsClick"></warehouseList>
      </div>
    </div>
    <el-dialog
      title="查找商品"
      :visible.sync="orderVisible"
      width="950px"
      v-el-drag-dialog
      :before-close="orderClose">
      <div style="position: relative;">
        <productTable ref="productList" @doubleClick="doubleClick" @addClick="addProductClick"></productTable>
      </div>
    </el-dialog>
    <el-dialog
      title="查找供应商"
      :visible.sync="supplierVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="supplierClose">
      <div style="position: relative;height: 63vh;overflow: auto">
        <supplierTable :key="times"  @doubleSupplier="doubleSupplier"></supplierTable>
      </div>
    </el-dialog>
    <el-footer class="el-footerBox">
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadOrder" style="margin-bottom: auto"></pagination>
    </el-footer>
  </el-container>
</template>

<script>
  import supplierTable from '../../components/SupplierTable/supplierList'
  import productTable from '@/components/ProductList/productList'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import { list as productList } from '@/api/product'
  import {list as supplierList} from '@/api/supplier'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import loadMore from '@/utils/more.js'
  import {EventBus} from '@/api/eventBus'
  import warehouseList from './components/list'
  import {list} from '@/api/warehouse'
  import Pagination from '@/components/Pagination';
  import utils from '../../utils/utils.js'

  export default {
    name: 'purchasein-list',
    directives: {loadMore,permission,elDragDialog},
    activated() {
      this.payLoads = new Date().getTime();
    },
    data() {
      return {
        suppliers:[],
        times:'',
        supplierName:'',
        productName:'',
        payLoads:'',
        supplierVisible:false,
        productOptions:[],
        queryClicked:false,
        orderVisible:false,
        warehouseForm: [],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        curHeight: null,
        queryType: false,
        query: {
          supplierId:'',
          productId:'',
          status: '',
          date: [],
          orderSn:'',
          sn: ''
        },
        keyword: {
          supplierId:'',
          productId:'',
          status: '',
          date: [],
          orderSn:'',
          sn: ''
        },
        pickerOptions: {//时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      };
    },
    components: {
      warehouseList, Pagination,productTable,supplierTable
    },
    created() {
      var _this = this
      this.loadOrder()
      this.loadSupplier('')
      EventBus.$on('purchasein-add', res => { // 监听新增完毕
        // 更新列表数组
        _this.warehouseForm.splice(0, 0, res)
      });
      EventBus.$on('purchasein-edit', res => { // 监听状态更新
        // 更新列表数组
        for (var i = 0; i < _this.warehouseForm.length; i++) {
          if (_this.warehouseForm[i].id == res.id) {
            _this.$set(this.warehouseForm, i, res)
          }
        }
      });
      EventBus.$on('purchasein-view', res => { // 监听新增完毕
        // 更新列表数组
        console.log(res)
        for (var i = 0; i < _this.warehouseForm.length; i++) {
          if (_this.warehouseForm[i].id == res.id) {
            _this.warehouseForm.splice(i,1)
          }
        }
      })
    },
    mounted() {
      this.comeIn();
      this.beforeMount()
    },
    methods: {
      addProductClick(data){
        if(data.length>1){
          this.productName=data[0].name
          this.query.productId=data[0].id
          this.orderVisible = false;
          this.$message({
            message: '只能查询一个商品',
            offset: 120,
            center: true
          })
        }else{
          this.productName=data[0].name
          this.query.productId=data[0].id
        }
      },
      doubleClick(val){
        this.productName=val.name
        this.query.productId=val.id
        this.orderVisible = false;
      },
      doubleSupplier(data){
        this.supplierName=data.name
        this.query.supplierId=data.id
        this.supplierVisible=false
      },
      supplierClose(){
        this.supplierVisible=false
      },
      orderClose(){
        this.orderVisible = false;
      },
      toAddProduct(){
        this.orderVisible = true;
      },
      changeProduct(data){
        if (!utils.isNull(data)){
          this.productName=data.name
          this.query.productId=data.id
        }else {
          this.query.productId=''
        }

      },
      toSearchSupplier(){
        this.times=new Date().getSeconds()
        this.supplierVisible=true
      },
      changeSupp(val){
        if (!utils.isNull(val)){
          this.supplierName=val.name
          this.query.supplierId=val.id
        }else {
          this.query.supplierId=''
        }

      },
      loadSupplier(query){
        let params=new URLSearchParams()
        params.append('name',query)
        supplierList(params).then(res=>{
          this.suppliers=res.data.data
        })
      },
      remoteMethod(query){
        this.loadSupplier(query)
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (_this.queryType == true) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 265//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 224//减去页面上固定高度height
            }
          })();
        };
      },
      comeIn() {
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 224//减去页面上固定高度height
      },
      getProductList () { // 加载商品
        productList().then(res => {
          res.data.data.forEach((option, index) => {

            this.$set(this.productOptions, index, option)
          })
        }).catch(err => {
          console.log(err)
        })
      },
      queryProduct (query) { // 查询商品
        this.productOptions = []
        productList({name: query}).then(res => {
          res.data.data.forEach((option, index) => {

            this.$set(this.productOptions, index, option)
          })
        }).catch(err => {
          console.log(err)
        })
      },
      loadOrder() {
        var _this = this;
        let params = new URLSearchParams();
        params.append('pageNum', _this.pageNum);
        params.append('pageSize', _this.pageSize);
        params.append('status', _this.keyword.status);
        params.append('productId',this.keyword.productId)
        params.append('supplierId',this.keyword.supplierId)
        if (this.query.date) {
          params.append('startDate', this.keyword.date.length > 0 ? this.keyword.date[0] : '');
          params.append('endDate', this.keyword.date.length > 0 ? this.keyword.date[1] : '');
        }
        params.append('sn', _this.keyword.sn);
        params.append('orderSn',_this.keyword.orderSn);
        params.append('warehouseType',1)
        list(params).then(response => {
          console.log(response)
          _this.warehouseForm = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          console.log('error!!')
        });
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == true) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 265//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 224//减去页面上固定高度height
        }
      },
      queryClick() {
        this.queryClicked=true
        setTimeout(()=>{
          this.queryClicked=false
        },300)
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadOrder()
      },
      resetClick() {
        this.query.date = [];
        this.query.status = '';
        this.query.sn = '';
        this.query.orderSn='';
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadOrder()
      },
      detailsClick(data) {
        this.$router.push({
          path: '/purchasein/view', query: {id: data}
        })
      },

    }
  }
</script>

<style scoped>

  .details_card {
    overflow: auto;
    padding-left: 20px;
    padding-right: 20px;
    box-sizing: border-box;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
  .el-input__inner {
    width: 100% !important;
  }
  .details_card:hover {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
  }
  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/ .el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
    flex-direction: column;
  }

  .report_header_left {
    width: 5px;
    height: 46px;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }

  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
